/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.openbookformat.obffinder.filters;

import org.openide.util.lookup.ServiceProvider;

/**
 *
 * @author matamh0a
 */
@ServiceProvider(service=Filter.class)
public class LineLengthFormatter extends ReplaceFilter {
    int lineLength = 80;
    
    public LineLengthFormatter() {
        name = "Line Length Formatter";
        findText = ".*?\n";
        replaceText = "<custom_code>";
        regExp = true;
        ignoreCase = false;
        useVariables = false;
        useIgonreNewLine = true;
        applyToAll = false;
        description = "Enforce line length";
    }

    @Override
    public String process(String text) {
        //check if the text need splitting
        if(lineLength < 1 
                || text.trim().startsWith("<")) {
            return text;
        }
        
        //remove repeated spaces, tabs, ....
        text = text.replaceAll("(\\s)\\1+", "$1");
        StringBuilder buff = new StringBuilder(text);
        
        int idx = -1; //location where to split
        int cutIdx = 0;
        while(buff.length() - cutIdx > lineLength) {
            idx = buff.substring(0, cutIdx + lineLength).lastIndexOf(" ");
            
            //not space found ==> search forward.
            if(idx == -1) {
                idx = cutIdx;
                while(cutIdx < buff.length() && buff.charAt(cutIdx) != ' '){
                    cutIdx++;
                }
            } else {   //found; 
                cutIdx = idx;
            }
            
            //add new text
            buff.replace(cutIdx, cutIdx + 1, "\n");
        }
        buff.append("<par />\n");
        return buff.toString();
    }
    
    public int getLineLength() {
        return lineLength;
    }

    public void setLineLength(int lineLength) {
        this.lineLength = lineLength;
    }
    
}
